<template>
	<view class="store-page">
		<!-- <nav-bar :title="titleEntrn" :showLeftIcon="true" :leftSlot="false"></nav-bar> -->
		<scroll-view
		  scroll-y="true"
		  class="content-box"
		>
			<view style="font-size: 24rpx; color: #1777ff;text-align: center;padding-top: 20rpx;" v-if="isApproved == 3">审核已拒绝，请重新发起申请</view>
			<uni-forms :rules="rules" :value="form" ref="form" validate-trigger="bind" err-show-type="undertext" label-width="400rpx">
				<view class="formTitle">
					<text>*</text>
					信息填写
				</view>
				<view class="basic-information">
					<uni-forms-item label="公司名称" label-width="200rpx" name="companyName">
						<input type="text" v-model="form.companyName" :disabled="isApproved == 2"
							placeholder="请填写" />
					</uni-forms-item>
					<uni-forms-item label="法人姓名" label-width="200rpx" name="legalPersonName">
						<input type="text" v-model="form.legalPersonName" :disabled="isApproved == 2"
							placeholder="请填写" />
					</uni-forms-item>
					<uni-forms-item label="法人电话" label-width="200rpx" name="legalPersonPhone">
						<input type="number" maxlength="11" v-model="form.legalPersonPhone" :disabled="isApproved == 2" placeholder="请填写"/>
					</uni-forms-item>
					<uni-forms-item label="业务负责人姓名" label-width="200rpx" name="businessLeaderName">
						<input type="text" v-model="form.businessLeaderName" :disabled="isApproved == 2" placeholder="请填写" />
					</uni-forms-item>
					<uni-forms-item label="业务负责人电话" label-width="200rpx" name="businessLeaderPhone">
						<input type="number" maxlength="11" :disabled="isApproved == 2" v-model="form.businessLeaderPhone" placeholder="请填写"/>
					</uni-forms-item>
					<!-- <uni-forms-item label="紧急联系人电话" label-width="300" name="emergencyContactPhone">
						<input type="text" maxlength="11" v-model="form.emergencyContactPhone" placeholder="请填写"/>
					</uni-forms-item> -->
					<uni-forms-item label="承运商列表" v-if="entryType == '2'" label-width="400rpx">
						<view class="flex-reverse" @click="selectEntry">
							<view class="selct-placeholder" v-if="form.companyId == ''">请选择</view>
							<view v-else>
								{{forrmatterCompany(form.companyId)}}
							</view>
							<u-icon name="arrow-right"></u-icon>
						</view>
						
					</uni-forms-item>
				</view>
				<view class="formTitle">
					<text>*</text>
					信息上传
				</view>
				<view class="information-upload">
					<uni-forms-item>
						<template slot="label">
							<view class="formTitle-item">营业执照+道路运输许可证</view>
						</template>
						<view class="imgs">
							<view class="imgs-item">
								<u-upload :fileList="fileImage.businessLicense" @afterRead="afterRead"
									@delete="deletePic" name="businessLicense" multiple :maxCount="1"
									:previewFullImage="false" width="274rpx" height="170rpx" :deletable="isApproved != 2">
									<image src="https://cdn.uviewui.com/uview/demo/upload/positive.png" mode="widthFix"></image>
								</u-upload>
								<text>营业执照</text>
							</view>
							<view class="imgs-item">
								<u-upload :fileList="fileImage.roadTransportPermit" @afterRead="afterRead"
									@delete="deletePic" name="roadTransportPermit" multiple :maxCount="1"
									:previewFullImage="false" width="274rpx" height="170rpx" :deletable="isApproved != 2">
									<image src="https://cdn.uviewui.com/uview/demo/upload/positive.png" mode="widthFix"></image>
								</u-upload>
								<text>道路运输许可证</text>
							</view>
							
						</view>
					</uni-forms-item>
					<uni-forms-item>
						<template slot="label">
							<view class="formTitle-item">法人身份证</view>
						</template>
						<view class="imgs">
							<view class="imgs-item">
								<u-upload :fileList="fileImage.legalPersonIdCardFront" @afterRead="afterRead"
									@delete="deletePic" name="legalPersonIdCardFront" multiple :maxCount="1"
									:previewFullImage="false" width="274rpx" height="170rpx" imageMode="scaleToFill" :deletable="isApproved != 2">
									<image src="https://cdn.uviewui.com/uview/demo/upload/positive.png" mode="widthFix"></image>
								</u-upload>
								<text>人像面</text>
							</view>
							<view class="imgs-item">
								<u-upload :fileList="fileImage.legalPersonIdCardBack" @afterRead="afterRead"
									@delete="deletePic" name="legalPersonIdCardBack" multiple :maxCount="1"
									:previewFullImage="false" width="274rpx" height="170rpx" :deletable="isApproved != 2">
									<image src="https://cdn.uviewui.com/uview/demo/upload/positive.png" mode="widthFix"></image>
								</u-upload>
								<text>国徽面</text>
							</view>
						</view>
					</uni-forms-item>
					<uni-forms-item>
						<template slot="label">
							<view class="formTitle-item">业务负责人身份证</view>
						</template>
						<view class="imgs">
							<view class="imgs-item">
								<u-upload :fileList="fileImage.businessLeaderIdCardFront" @afterRead="afterRead"
									@delete="deletePic" name="businessLeaderIdCardFront" multiple :maxCount="1"
									:previewFullImage="false" width="274rpx" height="170rpx" :deletable="isApproved != 2">
									<image src="https://cdn.uviewui.com/uview/demo/upload/positive.png" mode="widthFix"></image>
								</u-upload>
								<text>人像面</text>
							</view>
							<view class="imgs-item">
								<u-upload :fileList="fileImage.businessLeaderIdCardBack" @afterRead="afterRead"
									@delete="deletePic" name="businessLeaderIdCardBack" multiple :maxCount="1"
									:previewFullImage="false" width="274rpx" height="170rpx" :deletable="isApproved != 2">
									<image src="https://cdn.uviewui.com/uview/demo/upload/positive.png" mode="widthFix"></image>
								</u-upload>
								<text>国徽面</text>
							</view>
						</view>
					</uni-forms-item>
					<uni-forms-item>
						<template slot="label">
							<view class="formTitle-item">经营场地及车辆照片(最多6张)</view>
						</template>
						<view class="imgs imgs-more">
							<u-upload :fileList="fileImage.operationSitePhotos" @afterRead="afterRead"
								@delete="deletePic" name="operationSitePhotos" multiple :maxCount="sitePhotosMaxCount"
								:previewFullImage="false" width="200rpx" height="200rpx" :deletable="isApproved != 2"></u-upload>
						</view>
					</uni-forms-item>
				</view>
			</uni-forms>
		</scroll-view>
		<you-bottom-btn :btnConfig="bottomBtnConfig" v-if="isApproved != 2" @clickSubmit="clickSubmit"></you-bottom-btn>
		
		<u-popup :show="isSelectShow" :round="12" mode="bottom" @close="isSelectShow = false">
			<view class="select-cotent">
				<view class="select-list">
					<view class="select-item" v-for="(item, index) in operatingCompany" @click="selectItem(item)">
						{{item.companyName}}
					</view>
				</view>
				<view class="select-item" @click="isSelectShow = false">
					取消
				</view>
			</view>
		</u-popup>
	</view>
</template>

<script>
	import zlxlsUploadImg from "@/components/zlxls-upload-img/zlxls-upload-img.vue"
	import {
		baseUrl,
		baseImgUrl
	} from '@/config'
	import pageConfig from '@/config'
	import settleIn from '@/api/settleIn.js'
	import { getToken, removeToken } from '@/utils/auth'
	import { toast, showConfirm, tansParams } from '@/utils/common'
	import Common from '@/api/common.js'
	export default {
		name: 'Store',
		components: {zlxlsUploadImg},
		data() {
			return {
				titleEntrn: "物流承运商入驻",
				uploadUrl: baseUrl + "/common/upload",
				form: {
					companyName: '',
					legalPersonName: '',
					legalPersonPhone: '',
					businessLeaderName: '',
					businessLeaderPhone: '',
					// emergencyContactPhone: '',
					businessLicense: '',
					roadTransportPermit: '',
					legalPersonIdCardFront: '',
					legalPersonIdCardBack: '',
					businessLeaderIdCardFront: '',
					businessLeaderIdCardBack: '',
					operationSitePhotos: '',
					companyId: ''
				},
				fileImage: {
					businessLicense: [],
					roadTransportPermit: [],
					legalPersonIdCardFront: [],
					legalPersonIdCardBack: [],
					businessLeaderIdCardFront: [],
					businessLeaderIdCardBack: [],
					operationSitePhotos: [],
				},
				header:{
					'Authorization': 'Bearer ' + getToken()
				},
				params: {
				    cover:'',
				    slider:'',
				},
				entryType: 1,
				imageValue: '',
				rules: {
					legalPersonPhone: {
						rules: [{
								required: true,
								errorMessage: '请填写电话',
							},
							{
								minLength: 11,
								maxLength: 11,
								errorMessage: '请填写正确电话长度',
							}
						],
					},
					businessLeaderPhone: {
						rules: [{
								required: true,
								errorMessage: '请填写电话',
							},
							{
								minLength: 11,
								maxLength: 11,
								errorMessage: '请填写正确电话长度',
							}
						],
					},
					// emergencyContactPhone: {
					// 	rules: [{
					// 			required: true,
					// 			errorMessage: '请填写电话',
					// 		},
					// 		{
					// 			minLength: 11,
					// 			maxLength: 11,
					// 			errorMessage: '请填写正确电话长度',
					// 		}
					// 	],
					// },
				},
				bottomBtnConfig: [{
					text: '提交认证信息',
					class: 'confirm',
					funcName: 'clickSubmit'
				}],
				isSelectShow: false,
				operatingCompany: [],
				isApproved: 0,
				sitePhotosMaxCount: 6
			}
		},

		async onLoad(e) {
			console.log(this.fileImage)
			if(e.type) {
				this.entryType = e.type;
				this.titleEntrn = e.type == '1' ? '物流承运商入驻' : e.type == '2' ? '物流网点申请' : '汽车销售入驻';
				uni.setNavigationBarTitle({
				    title: this.titleEntrn
				});
			}
			if(this.entryType == '2') {
				this.getOperatingCompany();
			}
			this.getInfoAndImage();
		},
		async onShow() {
			
		},
		mounted() {
			const systemInfo = uni.getSystemInfoSync();
		},
		methods: {
			selectEntry() {
				if(this.isApproved == 2) return;
				this.isSelectShow = true;
			},
			getInfoAndImage() {
				Common.getInfo().then(res => {
					let {companyInfo, crmNetworkInfo} = res;
					this.isCarrier = 0;
					if(this.entryType == '1' && companyInfo && companyInfo.isApproved) {
						this.isApproved = companyInfo.isApproved;
						Object.keys(this.form).forEach(key => {
							this.$set(this.form, key, companyInfo[key]);
						})
						this.form.companyName = companyInfo.companyName;
						Object.keys(this.fileImage).forEach(key => {
							if(companyInfo[key] && companyInfo[key] != '' && companyInfo[key].split(',').length > 0) {
								let list = companyInfo[key].split(',');
								this.fileImage[key] = list.map(ele => {
									return {
										url: baseUrl + ele
									}
								})
							}
						})
						if(companyInfo.isApproved == 2) {
							this.sitePhotosMaxCount = this.fileImage.operationSitePhotos.length;
						}
						
					}
					if(this.entryType == '2' && crmNetworkInfo && crmNetworkInfo.isApproved) {
						this.isApproved = crmNetworkInfo.isApproved;
						Object.keys(this.form).forEach(key => {
							this.$set(this.form, key, crmNetworkInfo[key])
						})
						this.form.companyName = crmNetworkInfo.networkPointsName;
						Object.keys(this.fileImage).forEach(key => {
							if(crmNetworkInfo[key] && crmNetworkInfo[key] != '' && crmNetworkInfo[key].split(',').length > 0) {
								let list = crmNetworkInfo[key].split(',');
								this.fileImage[key] = list.map(ele => {
									return {
										url: baseUrl + ele
									}
								})
							}
						})
						if(crmNetworkInfo.isApproved == 2) {
							this.sitePhotosMaxCount = this.fileImage.operationSitePhotos.length;
						}
						
						console.log(this.fileImage)
					}
					
				})
			},
			uploaded(e) {
				console.log(e)
			},
			select(e) {
				console.log(e)
			},
			async clickSubmit() {
				Object.keys(this.fileImage).forEach(key => {
					if(this.fileImage[key].length > 0) {
						let list = this.fileImage[key].map(ele => {
							let url = ele.url;
							if(url.includes(baseUrl)) {
								url = url.replace(baseUrl, '');
							}
							return url;
						})
						this.$set(this.form, key, list.join(","))
					}
				})
				console.log(this.form);
				let res = await settleIn.addCertifica({...this.form, entryType: this.entryType, entryMode: 0});
				if(res.code == 200) {
					uni.showToast({
						title: "申请成功，请耐心等待审核",
						icon: 'none'
					});
					setTimeout(() => {
						uni.switchTab({
							url: '/pages/settleIn'
						})
					},1000)
				}
			},
			deletePic(event) {
				this.fileImage[`${event.name}`].splice(event.index, 1);
				console.log(this.fileImage[`${event.name}`])
			},
			// 获取承运商列表
			async getOperatingCompany() {
				let res = await settleIn.getAllCompaniesList({
					approvedStatus: 1
				});
				this.operatingCompany = res.rows;
			},
			// 新增图片
			async afterRead(event) {
				console.log(event)
				// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file);
				let fileListLen = this.fileImage[`${event.name}`].length;
				lists.map((item) => {
					this.fileImage[`${event.name}`].push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				})
				for (let i = 0; i < lists.length; i++) {
					try{
						const result = await this.uploadFilePromise(lists[i].url)
						// 返回给后端服务器的 结果需要赋值给 this.infoForm.image = result
						console.log(result, '上传图像result');
						let item = this.fileImage[`${event.name}`][fileListLen];
						this.fileImage[`${event.name}`].splice(fileListLen, 1, Object.assign(item, {
							status: result.code,
							message: result.code != '200' ? '上传失败' : '上传成功',
							url: result.fileName
						}))
						fileListLen++
					}catch(e){
						//TODO handle the exception
						this.fileImage[`${event.name}`].splice(fileListLen, 1)
					}
					
				}
				console.log(this.fileImage)
			},
			uploadFilePromise(url, index) {
				return new Promise((resolve, reject) => {
					let a = uni.uploadFile({
						url: baseUrl + '/common/upload', // 仅为示例，非真实的接口地址
						filePath: url,
						name: 'file',
						header: {
							'Authorization': 'Bearer ' + getToken()
						},
						formData: {},
						success: (respose) => {
							let res = respose.data && JSON.parse(respose.data);
							console.log(res, "resresresres")
							if(res.code == 401) {
								showConfirm('登录状态已过期，您可以继续留在该页面，或者重新登录?').then(reslv => {
								  if (reslv.confirm) {
								    removeToken()
								    uni.reLaunch({ url: '/subPages/login/index' })
								  }
								})
							} else if(res.code == 200) {
								setTimeout(() => {
									resolve(res)
								}, 1000)
							} else {
								uni.showToast({
									icon: 'none',
									title: '上传失败，请稍后再试'
								})
								reject("err")
							}
							
						},
						fail: (err) => {
							console.log(err,"err");
							
						}
					});
				})
			},
			selectItem(item) {
				this.$set(this.form, "companyId", item.id);
				this.isSelectShow = false;
			},
			forrmatterCompany(id) {
				let index = this.operatingCompany.findIndex(ele => ele.id == id);
				return index > -1 ? this.operatingCompany[index].companyName : id;
			}
		}
	}
</script>
<style lang="scss" scoped>
	/deep/.u-upload__wrap__preview {
		margin: 0;
	}
	.imgs-more {
		/deep/.u-upload__wrap__preview {
			margin-right: 10rpx;
			margin-bottom: 10rpx;
		}
	}
	.select-cotent {
		font-size: 34rpx;
		color: #161823;
		background: #f3f3f3;
		overflow: hidden;
		border-radius: 12rpx 12rpx 0 0;
		.select-list {
			margin-bottom: 16rpx;
			background: #fff;
			max-height: 40vh;
			overflow-y: auto;
		}
		.select-item {
			padding: 32rpx;
			text-align: center;
			background: #fff;
		}
	}
	.store-page {
		background: #f6f6f6;
		.content-box {
			padding: 0 28rpx;
			padding-bottom: 220rpx;
			height: 100vh;
			.formTitle {
				font-weight: 500;
				color: #1a1a1a;
				margin: 20rpx 0;
				font-size: 28rpx;
				text {
					color: red;
				}
			}
			.formTitle-item {
				font-weight: 500;
				color: #666;
				font-size: 28rpx;
				margin-bottom: 10rpx;
				margin-top: 30rpx;
			}

			.basic-information,
			.information-upload {
				background: #fff;
				padding: 10rpx 24rpx;
				border-radius: 10rpx;
			}
			.basic-information {
				input {
					height: 100rpx;
					font-size: 28rpx;
					text-align: right;
				}
			}
		}
	}
	.selct-placeholder {
		color: #999;
		font-size: 28rpx;
		text-align: right;
	}
	.flex-reverse {
		height: 100%;
		display: flex;
		justify-content: flex-end;
		align-items: center;
		line-height: 1;
	}
</style>
<style lang="scss">
	.basic-information {

		.uni-group__content,
		.information-upload {
			border-radius: 20rpx !important;

		}

		.uni-forms-item__label {
			width: 250rpx !important;
		}

		.uni-forms-item {
			align-items: center;
			margin: 0;
			border-bottom: 1px solid #e9e9e9;

			&:last-child {
				border: 0;
			}
		}
	}

	.information-upload {
		.uni-forms-item {
			display: block;

		}
	}

	.imgs {
		display: flex;
		justify-content: space-between;
		.imgs-item {
			width: 312rpx;
			background: #F6F6F6;
			padding: 30rpx 20rpx;
			padding-bottom: 16rpx;
			display: flex;
			flex-direction: column;
			align-items: center;
			border-radius: 8rpx;
			flex: 1;
			&:nth-child(2n + 1) {
				margin-right: 20rpx;
			}
			>text {
				color: #222;
				font-size: 24rpx;
				line-height: 1;
				padding-top: 16rpx;
			}
			image {
				width: 240rpx;
				height: 170rpx;
			}
		}
	}

	.msg--active {
		opacity: 1;
		transform: translateY(-100%);
	}
</style>